/**
 * @author 艾尼亚尔
 * @date 2025/8/18
 * @description 权限指令
 */
import type { ObjectDirective, DirectiveBinding } from 'vue';
import { hasPermission } from '@/utils/index.ts';
import { isArray, isObject } from "lodash";

function getPermissionValue(binding: DirectiveBinding): { value: string, isDisabled: boolean } {
  let value: string = '';
  let isDisabled = false;
  const bindVal = binding.value;
  if (isArray(bindVal)) {
    value = bindVal[0];
  } else if (isObject(bindVal)) {
    const obj = bindVal as { action?: string; effect?: string };
    value = obj.action || '';
    isDisabled = obj.effect === 'disabled';
  } else if (typeof bindVal === 'string') {
    value = bindVal;
  }
  return { value, isDisabled };
}

function handlePermission(el: HTMLElement, binding: DirectiveBinding) {
  if (binding.value == null) return;
  const { value, isDisabled } = getPermissionValue(binding);
  if (!hasPermission(value)) {
    if (isDisabled) {
      (el as HTMLButtonElement).disabled = true;
      el.classList.add('n-button--disabled');
    } else {
      if (el.parentNode) {
        el.parentNode.removeChild(el);
      }
    }
  } else {
    // 如果之前被禁用，权限恢复时移除禁用状态
    (el as HTMLButtonElement).disabled = false;
    el.classList.remove('n-button--disabled');
  }
}

export const permission: ObjectDirective = {
  mounted(el, binding) {
    handlePermission(el, binding);
  },
  updated(el, binding) {
    handlePermission(el, binding);
  }
}
